package com.paw.security.jwt.util;

import java.util.Date;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

/**
 * @author lvzihai
 * @date 2021/7/13
 **/
public class JwtTokenUtil {

  private static long tokenExpiration = 24 * 60 * 60 * 1000;
  private static String tokenSignKey = "123456";
  private static String userRoleKey = "userRole";

  public static String createToken (String userName) {
    return createToken(userName,"user");
  }

  public static String createToken (String userName, String role) {
    String token = Jwts.builder().setSubject(userName)
        .claim(userRoleKey, role)
        .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
        .signWith(SignatureAlgorithm.HS512, tokenSignKey).compressWith(CompressionCodecs.GZIP).compact();
    return token;
  }

  public static String getUserNameFromToken (String token) {
    String userName = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token).getBody().getSubject();
    return userName;
  }

  public static String getUserRoleFromToken (String token) {
    Claims claims = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token).getBody();
    String roles  = (String) claims.get(userRoleKey);
    return roles;
  }


}
